<template>
  <div
    ref="scrollWrap"
    class="scroll-view"
    :style="{ height }"
    style="overflow: hidden"
  >
    <el-scrollbar
      ref="scrollbar"
      :wrap-style="'height: '+ wrapHeight + ';'"
    >
      <slot />
    </el-scrollbar>
  </div>
</template>

<script>
import { Scrollbar } from 'element-ui'
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'

export default {
  name: 'ScrollView',
  components: {
    'el-scrollbar': Scrollbar
  },
  props: {
    height: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      barHeight: '',
      wrapHeight: ''
    }
  },
  mounted() {
    this.computeHeight()
    addResizeListener(this.$el, this.computeHeight)
  },
  beforeDestroy() {
    removeResizeListener(this.$el, this.computeHeight)
  },
  methods: {
    scrollTop(y) {
      if (typeof y === 'number') {
        this.$refs.scrollbar.$el.children[0].scrollTop = y
      }
      return this.$refs.scrollbar.$el.children[0].scrollTop
    },
    scrollToElement(el, offset = 0) {
      let topDistance = 0
      let element = el
      while (this.$refs.scrollbar.$el.children[0] !== element && element !== document.body) {
        topDistance += element.offsetTop
        element = element.parentNode
      }
      this.scrollTo(topDistance + offset)
    },
    computeHeight() {
      setTimeout(() => {
        if (this.$refs && this.$refs.scrollbar) {
          this.barHeight = this.$refs.scrollbar.$refs.wrap.style.marginBottom.replace(/^-/, '')
          const style = window.getComputedStyle(this.$refs.scrollWrap, null)
          this.wrapHeight = this.barHeight ? `calc(${style.height} + ${this.barHeight})` : style.height
          this.$nextTick(() => this.$refs.scrollbar.update())
        }
      }, 0)
    }
  }
}
</script>
